#include "sock.hpp"
#include "epoller.hpp"
#include "app_interface.hpp"
#include "util.hpp"
#include <string>
#include <cstdlib>

const int back_log = 5;

static void Usage(std::string proc)
{
    std::cout << "Usage: " << "\n\t" << proc << " port" << std::endl;
}

// ./epoll_server port
int main(int argc, char *argv[])
{
    if(argc != 2){
        Usage(argv[0]);
        exit(5);

    }
    uint16_t port = atoi(argv[1]);
    int listen_sock = ns_sock::Sock::Socket();

    //这个是与服务器listen sock相关
    listen_sock = ns_sock::Sock::Socket();
    ns_util::SetNonBlock(listen_sock);
    ns_sock::Sock::Bind(listen_sock, port);
    ns_sock::Sock::Listen(listen_sock, back_log);

    //这个是我们的Epoll事件管理器
    ns_epoll::Epoller epoller;
    epoller.InitEpoller();

    ns_epoll::EventItem item;
    item.sock = listen_sock;
    item.R = &epoller;

    //listen只需要关心读事件就行
    //accepter函数TODU
    item.ManagerCallBack(ns_appinterface::accepter, nullptr, nullptr); 

    //将我们的listen_sock,托管给epoller！
    epoller.AddEvent(listen_sock, EPOLLIN|EPOLLET, item);


    int timeout = 1000;
    while(true){
        epoller.Dispatcher(timeout);
    }


    return 0;
}

